package io.renren.data;

import cn.hutool.core.io.FileUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.renren.RenrenApplication;
import io.renren.modules.avanotes.component.FfmpegComponent;
import io.renren.modules.avanotes.dao.MovieSubtitleDao;
import io.renren.modules.avanotes.dao.SubtitleDetailsDao;
import io.renren.modules.avanotes.entity.MovieSubtitleEntity;
import io.renren.modules.avanotes.entity.SubtitleDetailsEntity;
import io.renren.modules.avanotes.service.MovieSubtitleService;
import io.renren.modules.avanotes.service.SubtitleDetailsService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.io.File;
import java.nio.charset.Charset;
import java.nio.file.DirectoryIteratorException;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;

/**
 * @author: xiaomi
 * @date: 2022/1/30
 * @description: 前期数据准备
 */
@RunWith(SpringRunner.class)
@SpringBootTest(classes = RenrenApplication.class)
@Slf4j
public class MovieImport {

    @Autowired
    MovieSubtitleDao msDao;

    @Autowired
    MovieSubtitleService msService;

    @Autowired
    SubtitleDetailsService sdService;

    @Autowired
    SubtitleDetailsDao sdDao;


    @Autowired
    FfmpegComponent ffmpegComponent;

    /**
     * 将第一季的数据导入到 DB
     */
    @Test
    public void s01e01DataImport2DB() {
        String path = "E:\\MyResources\\movie\\绝望的主妇\\绝望的主妇.Desperate.Housewives.S01-S08.Complete.Chi_Eng\\绝望的主妇.Desperate.Housewives.S01.Chi_Eng.HR-HDTV.AAC.1024X576.x264-YYeTs人人影视";
        //1.读取下面的文件，入库
        File file = new File(path);
        if (!file.isDirectory()) {
            //如果非目录
            return;
        }
        List<MovieSubtitleEntity> list = new ArrayList<>();
        //罗列下面的文件名称
        String[] fileNames = file.list();
        for (String fileName : fileNames) {
            File subFile = new File(path, fileName);
            String name = fileName;
            MovieSubtitleEntity entity = new MovieSubtitleEntity();
            entity.setFileName(name);
            if (subFile.isDirectory()) {
                //读取该目录下的结构
                String[] lastFileNames = subFile.list();
                for (String lastFileName : lastFileNames) {
                    File finallyFile = new File(subFile.getAbsoluteFile(), lastFileName);
                    if (lastFileName.endsWith("srt")) {
                        //字幕文件
                        entity.setSubtitleAbsolutePath(finallyFile.toString());
                        //读取内容
                        String content = FileUtil.readString(finallyFile, Charset.defaultCharset());
                        entity.setContent(content);
                    } else if (lastFileName.endsWith("mkv") || lastFileName.endsWith("mp4")) {
                        entity.setMovieAbsolutePath(finallyFile.toString());
                    } else {
                        log.error("文件格式不对！");
                    }
                }
                //添加数据
                list.add(entity);
            } else {
                log.error("目录格式不对！");
            }
        }
        //批量添加
        msService.saveBatch(list);
    }

    /**
     * 将字幕数据拆条
     * TODO duration 忘记处理
     */
    @Test
    public void s01e01DataDetails() {
        List<SubtitleDetailsEntity> ll = new ArrayList<>();
        //1. all list
        List<MovieSubtitleEntity> list = msDao.selectList(new QueryWrapper<>());
        for (MovieSubtitleEntity entity : list) {
            //SubtitleDetailsEntity detailsEntity = new SubtitleDetailsEntity();
            //2.1.id
            //detailsEntity.setMsId(entity.getId());
            String content = entity.getContent();
            //2.2. 将字符串转为 list 如果符号三行都匹配，就作为正常的内容进行保存
            String[] strings = content.split("\r\n");
            int index = 0;
            if (entity.getType() == 0) {
                //处理只有英文的
                //只有三行：序号，时间，英文
                SubtitleDetailsEntity temp = new SubtitleDetailsEntity();
                for (String string : strings) {
                    if (StringUtils.isBlank(string)) {
                        //遇到空行作为清零标志
                        index = 0;
                        if (temp.getMsId() != 0) {
                            ll.add(temp);
                        }
                        continue;
                    }
                    switch (index) {
                        case 0:
                            temp = new SubtitleDetailsEntity();
                            temp.setMsId(entity.getId());
                            try {
                                temp.setNum(Integer.parseInt(string.trim()));
                            } catch (Exception e) {
                                //log.error(e.getMessage());
                                log.info("舍弃：{}", string);
                                index--;
                            }
                            index++;
                            break;
                        case 1:
                            if (temp.getNum() == 0) {
                                log.error("没有填充 序号！");
                            }
                            String[] split = string.split("-->");
                            temp.setBeginTime(split[0].trim());
                            temp.setEndTime(split[1].trim());
                            index++;
                            break;
                        case 2:
                            if (StringUtils.isBlank(temp.getBeginTime())) {
                                log.error("没有填充 时间！");
                            }
                            if (StringUtils.isBlank(temp.getEnglish())) {
                                temp.setEnglish(string.trim());
                            } else {
                                temp.setEnglish(temp.getEnglish().concat(string.trim()));
                            }

                            //可能是多行的！
                            //index = 0;
                            //ll.add(temp);
                            break;
                    }
                }
            }


        }
        sdService.saveBatch(ll);
    }

    /**
     * 通过 ffmpeg 将视频进行拆条
     * ffmpeg -ss (beginTime) -t (duration) -accurate_seek -i (source) -codec copy (target)
     */
    @Test
    public void s01e01DataFfmpeg() {
        String targetDir = "E:\\File\\Video\\ReciteWordsByMovie\\DesperateHousewives\\S01";
        //1.获取集数
        List<MovieSubtitleEntity> list = msDao.selectList(new QueryWrapper<>());
        for (MovieSubtitleEntity entity : list) {
            String videoPath = entity.getMovieAbsolutePath();
            List<SubtitleDetailsEntity> ll = sdDao.selectList(new QueryWrapper<SubtitleDetailsEntity>().eq(SubtitleDetailsEntity.CN_MS_ID, entity.getId()));
            for (SubtitleDetailsEntity detailsEntity : ll) {
                if (StringUtils.isBlank(detailsEntity.getDuration())) {
                    continue;
                }
                String targetFileName = entity.getFileName().concat("-").concat(detailsEntity.getNum() + "");
                //ffmpeg
                File preDir = new File(Paths.get(targetDir, entity.getFileName()).toString());
                if (!preDir.exists()) {
                    preDir.mkdir();
                }

                String targetPath = Paths.get(targetDir, entity.getFileName(), targetFileName).toString().concat(".mp4");
                ffmpegComponent.executeExtractMedia(detailsEntity.getBeginTime().replace(",","."), detailsEntity.getDuration(),
                        videoPath, targetPath);

                SubtitleDetailsEntity updater = new SubtitleDetailsEntity();
                updater.setId(detailsEntity.getId());
                updater.setPath(targetPath);
                updater.setStatus(1);
                sdDao.updateById(updater);
            }
        }

    }

}
